package com.dk.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

//核心配置类
@Configuration
public class ShiroConfig {

    //创建过滤工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //拿到securityManager
        factoryBean.setSecurityManager(securityManager);

        //过滤器链 anon : 无需登录可以访问  authc : 必须登录才能访问 perms : 登录后必须授权才能访问 role : 登录后必须有角色才能访问
        Map<String, String> map = new LinkedHashMap<>(); //存储有序 linked单链表
//        map.put("/index", "authc");
        //退出
        map.put("/logout", "logout");
        map.put("/**", "anon");
        map.put("/user/**","authc");

        //拦截
//        map.put("/**", "authc");

        //设置跳转登录页面
        factoryBean.setLoginUrl("/user/toLogin");
        factoryBean.setUnauthorizedUrl("/unauthorized");

        //设置过滤器链
        factoryBean.setFilterChainDefinitionMap(map);

        return factoryBean;
    }

    //创建安全管理器setSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginUserRealm loginUserRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联自定义类
        securityManager.setRealm(loginUserRealm);
        return securityManager;
    }

    @Bean
    public LoginUserRealm loginUserRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginUserRealm loginUserRealm = new LoginUserRealm();
        //设置shiro的密码加密 关联加密
        loginUserRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginUserRealm;
    }

    //密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        //加密迭代的次数  111(222) 222(333) 333(444)
        matcher.setHashIterations(5);
        //加密方式
        matcher.setHashAlgorithmName("MD5");
        return matcher;
    }

    //开始thymeleaf整合shiro功能
    /*@Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }*/

}
